/** K线数据 **/

import { ref } from 'vue'
import * as pako from 'pako'
import { uuid } from '@util/utils'

export default function KlineGet() {
  const subKlineSocket = ref(null) // 订阅 k-line socket
  const reqKlineSocket = ref(null) // 请求 k-line socket
  const KlineWSUrl = 'wss://api.btcgateway.pro/linear-swap-ws' // K线数据 ws 地址

  /**
   * @classdesc  订阅 Web Socket 获取实时K线
   * @params params.params 订阅参数
   * @params params.recvCallback 回调函数
   **/
  const SubRequestWsKline = async (params, recvCallback) => {
    var Params = await GenerateRequsetParams(params)
    Params = Params.Sub
    var message = JSON.stringify(Params)
    subKlineSocket.value = new WebSocket(KlineWSUrl) // 创建连接
    subKlineSocket.value.binaryType = 'arraybuffer' // 设置返回类型
    subKlineSocket.value.onopen = async event => {
      subKlineSocket.value.send(message)
    }

    subKlineSocket.value.onmessage = async event => {
      var _text = pako.inflate(event.data, {
        to: 'string'
      })
      var recvData = JSON.parse(_text)

      if (recvData.ping) {
        subKlineSocket.value.send(
          JSON.stringify({
            pong: recvData.ping
          })
        )
      } else {
        if (!recvData.id) {
          recvCallback(recvData.tick)
        }
      }
    }

    subKlineSocket.value.onerror = () => {
      console.log('subKlineSocket.onerror')
      subKlineSocket.value.close()
    }
    subKlineSocket.value.onclose = () => {
      console.log('================ subKlineSocket 已暂停 ================')
    }
  }

  /**
   * @classdesc  请求 Web Socket 获取历史K线
   * @params params.params 订阅参数
   * @params params.recvCallback 回调函数
   **/
  const ReqRequestWsKline = async function(params, recvCallback) {
    var Params = await GenerateRequsetParams(params)
    Params = Params.Req
    var message = JSON.stringify(Params)

    reqKlineSocket.value = new WebSocket(KlineWSUrl) // 创建连接
    reqKlineSocket.value.binaryType = 'arraybuffer' // 设置ws数据返回类型
    reqKlineSocket.value.onopen = () => {
      reqKlineSocket.value.send(message)
    }

    reqKlineSocket.value.onmessage = async function(event) {
      var _text = pako.inflate(event.data, {
        to: 'string'
      })
      var recvData = JSON.parse(_text)
      if (recvData.ping) {
        reqKlineSocket.value.send(
          JSON.stringify({
            pong: recvData.ping
          })
        )
      } else {
        recvCallback(recvData)
      }
    }

    reqKlineSocket.value.onerror = function() {
      console.log('reqKlineSocket.onerror')
      reqKlineSocket.value.close()
    }
    reqKlineSocket.value.onclose = function() {
      console.log('================ reqKlineSocket 已暂停或刷新 ================')
    }
  }
  return {
    SubRequestWsKline,
    ReqRequestWsKline,
    subKlineSocket,
    reqKlineSocket
  }
}

/**
 * @classdesc  生成 K线 的订阅/请求参数
 * @params params.symbol 数字货币
 * @params params.period K线周期
 **/
const GenerateRequsetParams = async function(params) {
  const UUID = uuid()
  var MAP_PERIOD = new Map([
    [0, '1min'],
    [1, '5min'],
    [2, '15min'],
    [3, '30min'],
    [4, '60min'],
    [5, '4hour'],
    [6, '1day'],
    [7, '1week'],
    [8, '1mon']
  ])

  var MAP_TIME = new Map([
    [1, 1],
    [2, 5],
    [3, 15],
    [4, 30],
    [5, 60],
    [6, 300],
    [7, 800],
    [8, 2000],
    [9, 3000]
  ])

  var strPeriod = MAP_PERIOD.get(params.period)
  var mathTime = MAP_TIME.get(params.period + 1)

  var symbol = params.symbol

  var reqData = {
    req: `market.${symbol}.kline.${strPeriod}`,
    id: UUID
  }
  var subData = {
    sub: `market.${symbol}.kline.${strPeriod}`,
    id: UUID
  }

  var currentTime = getCurrentSecondTime()
  reqData['from'] = currentTime - 3600 * 24 * mathTime
  reqData['to'] = currentTime
  return { Req: reqData, Sub: subData }
}

/** 获取当前时区（utc+8）的秒数 **/
function getCurrentSecondTime() {
  const time = new Date().getTime() / 1000
  return Math.round(time)
}
